package com.wing.order.controller.admin;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wing.cabinet.service.CellInventoryInoutDetailService;
import com.wing.cabinet.utils.ExcelUtils;
import com.wing.common.utils.JsonResult;
import com.wing.common.utils.PageResult;
import com.wing.order.model.entity.OrderReceiveLoad;
import com.wing.order.model.request.OrderReceiveLoadForm;
import com.wing.order.model.response.OrderReceiveLoadVO;
import com.wing.order.service.OrderReceiveLoadService;
import com.wing.wcabinet.model.entity.WcabCellInventoryInout;
import com.wing.wcabinet.service.WcabCellInventoryInoutDetailService;
import com.wing.web.annotation.RequestObjectFieldIgnore;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *
 * @author
 */
@Validated
@Api(value = "Admin-上货数量管理", tags = "#/order/wcabOrderReceiveUnload")
@RestController("wcabOrderReceiveUnloadController")
@RequestMapping("order/admin/wcabOrderReceiveUnload")
@RequiredArgsConstructor
@Slf4j
public class WcabOrderReceiveUnloadController {

    private final OrderReceiveLoadService orderReceiveLoadService;

    @Autowired
    private CellInventoryInoutDetailService cellInventoryInoutDetailService;

    @Autowired
    private WcabCellInventoryInoutDetailService wcabCellInventoryInoutDetailService;


    @ApiOperation(value = "查询所有上货数量", notes = "搜索")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "第几页", defaultValue = "1", example = "1", dataType = "Integer", paramType = "query")
            ,@ApiImplicitParam(name = "limit", value = "每页多少条", defaultValue = "10", example = "10", dataType = "Integer", paramType = "query")
            ,@ApiImplicitParam(name = "sort", value="排序字段名", defaultValue = "create_time", example = "create_time", dataType = "String", paramType = "query")
            ,@ApiImplicitParam(name = "order", value="排序规则(asc:正序, desc:倒序)", defaultValue = "asc", example = "asc", dataType = "String", paramType = "query")
    })
    @GetMapping("/list")
    public PageResult<OrderReceiveLoadVO> list(
            @RequestParam(defaultValue = "1") Integer page
            ,@RequestParam(defaultValue = "10") Integer limit
            ,@RequestParam(defaultValue = "create_time") String sort
            ,@RequestParam(defaultValue = "desc") String order
            ,Long receiveDetailId
            ,String code
            ,String startTime
            ,String endTime
    ){

        Page<OrderReceiveLoad> pg = new Page<>(page, limit);
        Map<String, Object> params = new HashMap<>();

        //排序
        if (StringUtils.isNotBlank(sort) && StringUtils.isNotBlank(order)) {
            params.put("sort", StrUtil.toUnderlineCase(sort));
            params.put("order", order);
        }
        params.put("receiveDetailId",receiveDetailId);
        params.put("code",code);
        //搜索
        params.put("startCreateTime",startTime);
        params.put("endCreateTime",endTime);
        IPage<OrderReceiveLoadVO> list = orderReceiveLoadService.pageList4app(pg,params);
        return new PageResult<>(list.getRecords(), list.getTotal());
    }



    @ApiOperation(value = "添加上货数量", notes = "添加")
    @RequestObjectFieldIgnore({"id", "createTime", "remark"})
    @PostMapping("/add")
    public JsonResult add(@Validated(OrderReceiveLoadForm.Add.class) OrderReceiveLoadForm orderReceiveLoadForm) {
        try{
            orderReceiveLoadService.add(orderReceiveLoadForm);
            return JsonResult.success("添加成功");
        }catch (Exception e){
            log.error("receive load fail",e);
            return JsonResult.fail("添加失败");
        }
    }






    @ApiOperation(value = "修改上货数量", notes = "修改")
    @PutMapping("/update")
    public JsonResult update(@Validated(OrderReceiveLoadForm.Update.class) OrderReceiveLoadForm orderReceiveLoadForm) {
        OrderReceiveLoad orderReceiveLoad = orderReceiveLoadService.getById(orderReceiveLoadForm.getId());
        if(orderReceiveLoad == null){
        return JsonResult.fail("修改失败！");
        }
        CopyOptions copyOptions = CopyOptions.create()
        .setEditable(OrderReceiveLoad.class)
        .setIgnoreError(true)
        .setIgnoreNullValue(true);
        BeanUtil.copyProperties(orderReceiveLoadForm, orderReceiveLoad, copyOptions);
        if (orderReceiveLoadService.updateById(orderReceiveLoad)) {
            return JsonResult.success("修改成功！");
        }
        return JsonResult.fail("修改失败！");
    }



@ApiOperation(value = "删除上货数量", notes = "删除")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "orderReceiveLoadId", value = "上货数量id", required = true, dataType = "Integer", paramType = "path")
    })
    @DeleteMapping("/{id}" )
    public JsonResult delete(@PathVariable("id") Long orderReceiveLoadId) {
        if (orderReceiveLoadService.removeById(orderReceiveLoadId)) {
            return JsonResult.success("删除成功");
        }
        return JsonResult.fail("删除失败");
    }


    @ApiOperation(value = "上货", notes = "添加")
    @RequestObjectFieldIgnore({"id", "createTime", "remark"})
    @PostMapping("/load")
    public JsonResult load(@Validated(OrderReceiveLoadForm.Add.class) OrderReceiveLoadForm orderReceiveLoadForm) {
        try{
            cellInventoryInoutDetailService.inventoryIn(orderReceiveLoadForm);
            return JsonResult.success("上货成功");
        }catch (Exception e){
            log.error("receive load fail",e);
            return JsonResult.fail(e.getMessage());
        }
    }

    @ApiOperation(value = "上货", notes = "添加")
    @RequestObjectFieldIgnore({"id", "createTime", "remark"})
    @PostMapping("/loadSimple")
    public JsonResult loadSimple(@Validated(OrderReceiveLoadForm.Add.class) OrderReceiveLoadForm orderReceiveLoadForm) {
        try{
            cellInventoryInoutDetailService.inventoryIn4Simple(orderReceiveLoadForm);
            return JsonResult.success("上货成功");
        }catch (Exception e){
            log.error("receive load fail",e);
            return JsonResult.fail(e.getMessage());
        }
    }


    @ApiOperation(value = "上货", notes = "添加")
    @RequestObjectFieldIgnore({"id", "createTime", "remark"})
    @PostMapping("/batchLoadSimple")
    public JsonResult batchLoadSimple(@Validated(OrderReceiveLoadForm.Add.class) @RequestBody OrderReceiveLoadForm orderReceiveLoadForm) {
        try{
            cellInventoryInoutDetailService.inventoryIn4BatchSimple(orderReceiveLoadForm);
            return JsonResult.success("上货成功");
        }catch (Exception e){
            log.error("receive load fail",e);
            return JsonResult.fail(e.getMessage());
        }
    }

    @ApiOperation(value = "上货", notes = "添加")
    @RequestObjectFieldIgnore({"id", "createTime", "remark"})
    @PostMapping("/wcab/load")
    public JsonResult wcabLoad(@Validated(OrderReceiveLoadForm.Add.class) @RequestBody OrderReceiveLoadForm orderReceiveLoadForm) {
        try{
            wcabCellInventoryInoutDetailService.inventoryIn4Batch(orderReceiveLoadForm);
            return JsonResult.success("上货成功");
        }catch (Exception e){
            log.error("receive load fail",e);
            return JsonResult.fail(e.getMessage());
        }
    }

    @ApiOperation(value = "下货", notes = "添加")
    @RequestObjectFieldIgnore({"id", "createTime", "remark"})
    @PostMapping("/wcab/unload")
    public JsonResult wcabUnload(@Validated(OrderReceiveLoadForm.Add.class)@RequestBody OrderReceiveLoadForm orderReceiveLoadForm) {
        try{
            orderReceiveLoadForm.setType(OrderReceiveLoad.Type.selfBatchUnloadSimple);
            orderReceiveLoadForm.setOperationType(WcabCellInventoryInout.OperationType.unload);
            wcabCellInventoryInoutDetailService.inventoryOut4Batch(orderReceiveLoadForm);
            return JsonResult.success("下货成功");
        }catch (Exception e){
            log.error("receive load fail",e);
            return JsonResult.fail(e.getMessage());
        }
    }

    @ApiOperation(value = "下货", notes = "添加")
    @RequestObjectFieldIgnore({"id", "createTime", "remark"})
    @PostMapping("/unload")
    public JsonResult unload(@Validated(OrderReceiveLoadForm.Add.class) OrderReceiveLoadForm orderReceiveLoadForm) {
        try{
            cellInventoryInoutDetailService.inventoryOut4Simple(orderReceiveLoadForm);
            return JsonResult.success("下货成功");
        }catch (Exception e){
            log.error("receive load fail",e);
            return JsonResult.fail(e.getMessage());
        }
    }

    @ApiOperation(value = "下货", notes = "添加")
    @RequestObjectFieldIgnore({"id", "createTime", "remark"})
    @PostMapping("/batchUnload")
    public JsonResult batchUnload(@Validated(OrderReceiveLoadForm.Add.class)@RequestBody OrderReceiveLoadForm orderReceiveLoadForm) {
        try{
            cellInventoryInoutDetailService.inventoryOut4BatchSimple(orderReceiveLoadForm);
            return JsonResult.success("下货成功");
        }catch (Exception e){
            log.error("receive load fail",e);
            return JsonResult.fail(e.getMessage());
        }
    }

    @ApiOperation(value = "导出上货记录数据")
    @GetMapping("/export")
    public void export(HttpServletResponse response, String startCreateTime, String endCreateTime){
        List<OrderReceiveLoadVO> orderReceiveLoadVOList = new ArrayList<>();
        if ("".equals(startCreateTime) || "".equals(endCreateTime)){
            log.error("上货时间为空："+startCreateTime);
        }
        endCreateTime = endCreateTime+" 23:59:59";
        Map paramsMap = new HashMap();
        paramsMap.put("startCreateTime",startCreateTime);
        paramsMap.put("endCreateTime",endCreateTime);

        orderReceiveLoadVOList = orderReceiveLoadService.ecxportList(paramsMap);

        //导出
        ExcelUtils.export(response,"上货记录",orderReceiveLoadVOList, OrderReceiveLoadVO.class);
    }
}
